import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'

export function encryp(key: string, iv: string, data: string) {
  if (typeof data === 'object') {
    // 如果传入的data是json对象，先转义为json字符串
    data = JSON.stringify(data)
  }
  // 统一将传入的字符串转成UTF8编码
  const dataHex = CryptoJS.enc.Utf8.parse(data) // 需要加密的数据
  const keyHex = CryptoJS.enc.Utf8.parse(key) // 秘钥
  const ivHex = CryptoJS.enc.Utf8.parse(iv) // 偏移量
  const encrypted = CryptoJS.AES.encrypt(dataHex, keyHex, {
    iv: ivHex,
    mode: CryptoJS.mode.CTR, // 加密模式
    padding: CryptoJS.pad.NoPadding
  })
  const encryptedVal = encrypted.ciphertext.toString()
  return encryptedVal //  返回加密后的值
}
// 解密数据
export function decrypt(key: string, iv: string, encryptedVal: string) {
  /*
      传入的key和iv需要和加密时候传入的key一致  
    */
  // 统一将传入的字符串转成UTF8编码
  const encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedVal)
  const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
  const keyHex = CryptoJS.enc.Utf8.parse(key) // 秘钥
  const ivHex = CryptoJS.enc.Utf8.parse(iv) // 偏移量
  const decrypt = CryptoJS.AES.decrypt(srcs, keyHex, {
    iv: ivHex,
    mode: CryptoJS.mode.CTR,
    padding: CryptoJS.pad.NoPadding
  })
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr
}
export function encryptedData(data: string) {
  // 新建JSEncrypt对象
  const encryptor = new JSEncrypt()
  let key = ``
  encryptor.setPublicKey(key) // 加密数据
  return encryptor.encrypt(data).toString()
}